import { message } from 'ant-design-vue';
import 'ant-design-vue/es/message/style/css';
import useImageUploader from '@/composable/upload-image';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import CropperImageView from '@components/public/CropperImageView.vue';
import { useI18n } from 'vue-i18n';

export default function useCropperModal() {
  const { t } = useI18n();

  const { uploadImage } = useImageUploader(t, "avater");
  
  const showCropModal = (imageUrl, onAvaterUploaded) => {
    const modal = Modal.info({
      title: t('operations.cropAvater'),
      content: createVNode(CropperImageView, {imageUrl, onImageCropped: (canvas) => { onImageCropped(canvas, onAvaterUploaded); modal.destroy();}}),
      cancelButtonProps: {style: {display: 'none'}},
      okButtonProps: {style: {display: 'none'}},
    })
  }

  const onImageCropped = (canvas, callback) => {
    canvas.toBlob((blob) => {
      const file = new File([blob], "cropped.jpg");
      uploadImage({
        file,
        onSuccess: (resp) => {
          callback(resp.data[0]);
        },
        onError: (e) => {
          message.error(`上传失败：${e}`);
        }
      });
    }, 'image/jpeg', 0.6);
  }

  return { showCropModal };
}